from django import forms
from django.contrib.auth.models import User
from .models import UserProfile
from django.core.exceptions import ValidationError
import re

class UserRegistrationForm(forms.ModelForm):
    username = forms.CharField(
        label='用户名',
        max_length=150,
        error_messages={
            'required': '用户名不能为空。',
            'max_length': '用户名不能超过150个字符。',
        }
    )
    email = forms.EmailField(
        label='邮箱',
        error_messages={
            'invalid': '请输入合法的邮箱地址。',
            'required': '邮箱不能为空。',
        }
    )

    password = forms.CharField(label='密码', widget=forms.PasswordInput)
    password2 = forms.CharField(label='确认密码', widget=forms.PasswordInput)
    security_question = forms.CharField(label='安全问题', max_length=255, help_text='例如：您的小学名称是什么？')
    security_answer = forms.CharField(label='安全答案', max_length=255)

    class Meta:
        model = User
        fields = ('username', 'email')  # 必须用模型字段名

    # 用户名唯一性校验，抛出中文错误
    def clean_username(self):
        username = self.cleaned_data.get('username')
        if User.objects.filter(username=username).exists():
            raise ValidationError("该用户名已存在，请使用其他用户名。")
        return username

    # 邮箱校验
    def clean_email(self):
        email = self.cleaned_data.get('email')
        pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        if not re.match(pattern, email):
            raise ValidationError("请输入合法的邮箱地址。")
        if User.objects.filter(email=email).exists():
            raise ValidationError("该邮箱已被注册，请使用其他邮箱。")
        return email

    # 密码确认校验
    def clean_password2(self):
        cd = self.cleaned_data
        if cd.get('password') != cd.get('password2'):
            raise ValidationError('密码不匹配。')
        return cd['password2']
